package simportal.controller;

import java.io.PrintWriter;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import simportal.service.TreeMenuService;

import com.cfuture08.eweb4j.component.DivPageComp;
import com.cfuture08.eweb4j.component.dwz.DWZUtil;
import com.cfuture08.eweb4j.component.dwz.vo.NavMenu;
import com.cfuture08.eweb4j.component.dwz.vo.TreeMenu;
import com.cfuture08.eweb4j.mvc.annotation.Controller;
import com.cfuture08.eweb4j.mvc.annotation.Param;
import com.cfuture08.eweb4j.mvc.annotation.RequestMapping;
import com.cfuture08.eweb4j.mvc.annotation.Result;
import com.cfuture08.eweb4j.mvc.annotation.Singleton;
import com.cfuture08.eweb4j.mvc.annotation.ValField;
import com.cfuture08.eweb4j.mvc.annotation.Validator;
import com.cfuture08.eweb4j.orm.dao.factory.DAOFactory;

@Controller
@Singleton
@RequestMapping("admin/treeMenus")
public class TreeMenuControl {
	private static final String model = "treeMenus";
	// 树形菜单服务类
	private static final TreeMenuService service = new TreeMenuService();
	private static final String success = DWZUtil.getSuccessJson("操作成功",
			"xssysxcd", "treeMenus/list", "reloadTab", "显示所有树形菜单").toString();

	/**
	 * GET|POST方式,返回某个导航菜单下的所有树形菜单列表，json格式
	 * 
	 * @param out
	 * @return
	 */
	@RequestMapping(value = "/{navMenuId}/suggest.json", method = "GET|POST")
	@Validator("int")
	@ValField(message = { "导航菜单ID应该为数字格式" }, name = { "navMenuId" })
	public String suggestJsonHandler(
			@Param(value = "treeMenuId", init = "-1") Integer tmid,
			@Param("navMenuId") Integer navMenuId, PrintWriter out) {
		out.print(service.getTreeMenusByNavMenuId(tmid, navMenuId));
		return null;
	}

	/**
	 * 批量删除
	 * 
	 * @param ids
	 * @param out
	 * @return
	 */
	@RequestMapping(value = "/batchRemove", method = "DELETE", showValErr = "dwzJson")
	@Validator("required")
	@ValField(name = "ids", message = "请选择要删除的信息")
	public String batchRemoveHandler(@Param("ids") Integer[] ids,
			PrintWriter out) {
		String info;
		String error = service.batchRemove(ids);
		if (error == null)
			info = success;
		else
			info = DWZUtil.getFailedJson(error).toString();
		out.print(info);
		return null;
	}

	/**
	 * 删除
	 * 
	 * @param id
	 * @param out
	 * @return
	 */
	@RequestMapping(value = "/{id}", method = "DELETE", showValErr = "dwzJson")
	@Validator("required")
	@ValField(name = "id", message = "请选择要删除的信息")
	public String removeHandler(@Param("id") Integer id, PrintWriter out) {
		return this.batchRemoveHandler(new Integer[] { id }, out);
	}

	/**
	 * 列表显示
	 * 
	 * @param p
	 * @param n
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/list", method = "GET|POST")
	@Result(name = { "success" }, location = { "list.jsp" })
	public String listHandler(@Param(value = "pageNum", init = "1") int p,
			@Param(value = "numPerPage", init = "20") int n,
			HttpServletRequest request) {
		List<TreeMenu> pojos = service.getPageWithCascade(p, n);
		if (pojos != null) {
			request.setAttribute("model", model);
			request.setAttribute("pojos", pojos);
			// 分页组件
			request.setAttribute("dpc",
					new DivPageComp(p, n, service.countAll(), 10));
			request.setAttribute("random", Math.random());
		}
		return "success";
	}

	/**
	 * 查询关键字
	 * 
	 * @param keyword
	 * @param p
	 * @param n
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/search", method = "GET|POST")
	@Result(name = { "success" }, location = { "list.jsp" })
	public String searchKeyword(@Param("keyword") String keyword,
			@Param(value = "pageNum", init = "1") int p,
			@Param(value = "numPerPage", init = "20") int n,
			HttpServletRequest request) {
		if (keyword == null || keyword.length() == 0) {
			return this.listHandler(p, n, request);
		}
		request.setAttribute("model", model);
		request.setAttribute("pojos", service.searchByKeywordAndPaging(
				new String[] { "name" }, keyword, p, n, 0));
		request.setAttribute("keyword", keyword);
		List<TreeMenu> list = service.searchByKeywordAndPaging(new String[] {
				"name", "href" }, keyword, -1, -1, 0);
		long count = 0;
		if (list != null) {
			count = list.size();
		}
		// 分页组件
		request.setAttribute("dpc", new DivPageComp(p, n, count, 10));
		request.setAttribute("random", Math.random());
		return "success";
	}

	/**
	 * 分页显示，数据返回到lookup.jsp中
	 * 
	 * @param p
	 * @param n
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/{navMenuId}/lookup", method = "GET|POST")
	@Result(name = "success", location = { "lookup.jsp" })
	public String lookupHandler(
			@Param(value = "treeMenuId", init = "-1") Integer tmid,
			@Param(value = "navMenuId") Integer navMenuId,
			@Param(value = "pageNum", init = "1") int p,
			@Param(value = "numPerPage", init = "20") int n,
			HttpServletRequest request) {
		return this.lookupKeyword(tmid, navMenuId, "", p, n, request);
	}

	/**
	 * 查询关键字，数据返回到lookup.jsp页面中
	 * 
	 * @param keyword
	 * @param p
	 * @param n
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/{navMenuId}/lookupSearch", method = "GET|POST")
	@Result(name = { "success" }, location = { "../lookup.jsp" })
	public String lookupKeyword(
			@Param(value = "treeMenuId", init = "-1") Integer tmid,
			@Param("navMenuId") Integer navMenuId,
			@Param("keyword") String keyword,
			@Param(value = "pageNum", init = "1") int p,
			@Param(value = "numPerPage", init = "20") int n,
			HttpServletRequest request) {
		List<TreeMenu> pojos = service
				.getTreeMenusByKeywordAndNavMenuIdAndPaging(keyword, tmid,
						navMenuId, p, n);
		request.setAttribute("pojos", pojos);
		request.setAttribute("navMenuId", navMenuId);
		request.setAttribute("model", model);
		request.setAttribute("keyword", keyword);
		List<TreeMenu> countResult = service
				.getTreeMenusByKeywordAndNavMenuIdAndPaging(keyword, tmid,
						navMenuId, -1, -1);
		// 计数用于分页
		long count = countResult == null ? 0 : countResult.size();
		// 分页组件
		request.setAttribute("dpc", new DivPageComp(p, n, count, 10));
		request.setAttribute("random", Math.random());
		return "success";
	}

	/**
	 * GET|POST方式，跳转到添加页面
	 * 
	 * @return
	 */
	@RequestMapping(value = "/new", method = "GET|POST")
	public String addHandler(HttpServletRequest request) {
		request.setAttribute("model", model);
		return "add.jsp";
	}

	/**
	 * 添加
	 * 
	 * @param pojo
	 * @param out
	 * @return
	 */
	@RequestMapping(value = "/", method = "POST", showValErr = "dwzJson")
	@Validator(value = { "int", "required" })
	@ValField(index = { 0, 1 }, message = { "排序项只能输入数字", "导航菜单不能为空" }, name = {
			"rank", "navMenus.dwz_navMenu2.navMenuId" })
	public String createHandler(
			@Param("navMenus.dwz_navMenu2.navMenuId") Integer navMenuId,
			@Param(value = model + ".dwz_treeMenu2.treeMenuId", init = "0") Integer pid,
			@Param("reload") String reload, TreeMenu pojo, PrintWriter out) {
		if ("on".equals(reload)) {
			pojo.setReloadFlag("1");
		} else {
			pojo.setReloadFlag("0");
		}

		NavMenu navMenu = new NavMenu();
		navMenu.setNavMenuId(navMenuId);
		TreeMenu parent = new TreeMenu();
		parent.setTreeMenuId(pid);
		pojo.setNavMenu(navMenu);
		pojo.setParent(parent);
		String error = service.createWithCascade(pojo);
		String info;
		if (error == null)
			info = DWZUtil.getSuccessJson("操作成功", "xssysxcd", "treeMenus/list",
					"closeCurrent", "显示所有树形菜单").toString();
		else
			info = DWZUtil.getFailedJson(error).toString();
		out.print(info);
		return null;
	}

	/**
	 * GET|POST方式打开编辑页面
	 * 
	 * @return
	 */
	@RequestMapping(value = "/{id}/edit", method = "GET|POST", showValErr = "dwzJson")
	@Validator("required")
	@ValField(message = { "请选择要编辑的信息" }, name = { "id" })
	public String editHandler(@Param("id") Integer id,
			HttpServletRequest request) {
		TreeMenu pojo = service.getOne(id);
		if (pojo != null) {
			if ("1".equals(pojo.getReloadFlag())) {
				pojo.setReloadFlag("checked");
			} else {
				pojo.setReloadFlag("");
			}
			DAOFactory.getCascadeDAO().select(pojo, "parent", "navMenu");// 将几个与之有关系的属性数据查询出来
			request.setAttribute("model", model);
			request.setAttribute("pojo", pojo);
		}

		return "../edit.jsp";
	}

	/**
	 * 修改
	 * 
	 * @param navMenu
	 * @param out
	 * @return
	 */
	@RequestMapping(value = "/{treeMenuId}", method = "PUT", showValErr = "dwzJson")
	@Validator(value = { "required", "int" })
	@ValField(index = { 1, 0, 1, 1 }, message = { "导航菜单ID应该为数字", "请选择要编辑的信息",
			"排序项只能输入数字", "父菜单ID应该为数字" }, name = {
			"navMenus.dwz_navMenu.navMenuId", "treeMenuId", "rank",
			model + ".dwz_treeMenu.treeMenuId" })
	public String updateHandler(
			@Param(model + ".dwz_treeMenu.treeMenuId") Integer pid,
			@Param("navMenus.dwz_navMenu.navMenuId") Integer navMenuId,
			@Param("reload") String reload, HttpServletRequest request,
			TreeMenu pojo, PrintWriter out) {

		// 自己不能成为自己的父菜单
		if (pid.equals(pojo.getTreeMenuId())) {
			out.print(DWZUtil.getFailedJson("不能选择自己作为父菜单。"));
			return null;
		}

		if ("on".equals(reload)) {
			pojo.setReloadFlag("1");
		} else {
			pojo.setReloadFlag("0");
		}
		NavMenu navMenu = new NavMenu();
		navMenu.setNavMenuId(navMenuId);
		TreeMenu parent = new TreeMenu();
		parent.setTreeMenuId(pid);
		pojo.setNavMenu(navMenu);
		pojo.setParent(parent);
		String error = service.updateByCascade(pojo);
		String info;
		if (error == null)
			info = DWZUtil.getSuccessJson("操作成功", "xssysxcd", "treeMenus/list",
					"closeCurrent", "显示所有树形菜单").toString();
		else
			info = DWZUtil.getFailedJson(error).toString();
		out.print(info);
		return null;
	}
}
